package com.luoyulin.linkedlist;

import java.util.TreeMap;

/**
 * @author luoyulin
 * @create 2022-01-14 19:07
 **/
public class Josephu {
    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        System.out.println("------遍历操作------");
        circleSingleLinkedList.showList();
        System.out.println("------出圈操作------");
        circleSingleLinkedList.countBot(1,2,5);

    }
}


//创建环形链表
class CircleSingleLinkedList{
    private Boy first = new Boy(-1);
    //添加节点形成环形
    public void addBoy(int nums){
        if(nums < 1){
            System.out.println("nums不正确");
            return;
        }
        Boy curBoy = null;
        //创建环形链表
        for (int i = 1; i <= nums ; i++) {
            Boy boy = new Boy(i);
            if(i == 1){
                first = boy;
                first.setNext(first);//成环
                curBoy = first;//cur指向第一个小孩
            } else{
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }
    }

    //遍历环形链表
    public void showList(){
        if(first == null){
            System.out.println("没有节点");
        }
        //first不能动，要使用辅助指针
        Boy curBoy = first;
        while (true){
            System.out.printf("小孩编号%d\n",curBoy.getNo());
            if(curBoy.getNext() == first){
                break;
            }
            curBoy = curBoy.getNext();//后移
        }
    }

    //出圈 startNo 开始节点 countNum隔多少个出圈，nums有多少个节点
    public void countBot(int startNo,int countNum,int nums){
        //校验
        if(first == null || startNo < 1 || startNo > nums){
            System.out.println("输入有误");
        }
        //辅助指针
        Boy temp = first;
        while (true){
            if(temp.getNext() == first){
                break;
            }
            temp = temp.getNext();
        }
        for (int i = 0; i < startNo - 1; i++) {
            first = first.getNext();
            temp = temp.getNext();
        }
        while (true){
            if(temp == first){
                break;
            }
            for(int j = 0;j < countNum - 1;j++){
                first = first.getNext();
                temp = temp.getNext();
            }
            System.out.printf("小孩%d出圈\n",first.getNo());
            first = first.getNext();
            temp.setNext(first);
        }
        System.out.printf("最后的时%d",first.getNo());
    }
}

//创建相当于节点类
class Boy{
    private int no;
    private Boy next;
    public Boy(int no){
        this.no = no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public void setNext(Boy next) {
        this.next = next;
    }

    public Boy getNext() {
        return next;
    }

    public int getNo() {
        return no;
    }
}
